<template>
  <div>
    
    <el-form ref="form" :model="spuFrom" label-width="80px">
      <el-form-item label="SPU名称">
        <el-input v-model="spuFrom.name" placeholder="SPU名称"></el-input>
      </el-form-item>
      <el-form-item label="品牌">
        <el-select v-model="spuFrom.brand_id" :placeholder="spuFrom.brand_id?spuFrom.brand_id :'没有品牌ID'">
          <el-option
            :label="item.name"
            :value="`${item.id}`"
            v-for="item in brandList"
            :key="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="SPU描述">
        <el-input
          v-model="spuFrom.goods_brief"
          type="textarea"
          :rows="4"
          placeholder="SPU描述"
          width="300"
        >
        </el-input>
      </el-form-item>

      <!-- 上传图片 -->
      <el-form-item label="SPU图片">
        <!-- <el-upload name="imgfile" :action="`/dev-api/goodsPic${category_id}`"  list-type="picture-card" :auto-upload="false" > -->
        <el-upload
          name="imgfile"
          :action="`/dev-api/goodsPic/${category_id}`" 
          list-type="picture-card"
          :file-list="imageList"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :on-success="picsUpdate"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%"  :src="dialogImageUrl" />
        </el-dialog>
      </el-form-item>

      <!-- <el-form-item label="销售属性">
        <el-select v-model="temp" :placeholder="attributeList.length > 1?`你还有${attributeList.length}属性选择`:'没有分类属性可以选择'">
      
          <el-option
            :label="attribute.name"
            :value="`${attribute.name}:${attribute.id}`"
            v-for="attribute in attributeList"
            :key="attribute.id"
          ></el-option>
        </el-select>
        <el-button type="primary" icon="el-icon-plus" @click="addSaleAttribute" :disabled="!temp.length > 0">添加销售属性</el-button>
      </el-form-item> -->
      
      <el-form-item label="销售属性">
        <el-select v-model="temp" :placeholder="unUseAttri.length > 1?`你还有${unUseAttri.length}属性选择`:'没有分类属性可以选择'">
          <!-- 销售属性 -->
          <el-option
            :label="attribute.name"
            :value="`${attribute.name}:${attribute.id}`"
            v-for="attribute in unUseAttri"
            :key="attribute.id"
          ></el-option>
        </el-select>
        <el-button type="primary" icon="el-icon-plus" @click="addSaleAttribute" :disabled="!temp.length > 0">添加销售属性</el-button>
      </el-form-item>

      <el-form-item>
        <el-table :data="defaultAttri" border style="width: 100%">
          <el-table-column type="index" label="序号" width="100" align="center">
          </el-table-column>
          <el-table-column prop="name" label="属性名" width="180">
          </el-table-column>
          <el-table-column prop="attributeList" label="属性值名称列表">
            <!-- tag -->
            <template slot-scope="{row,$index}">
              <el-tag :key="tag.id"
              v-for="(tag,index) in row.attri"
              closable
              :disable-transitions="false"
              @close="row.attri.splice(index,1)">
              {{tag.value}}
              
            </el-tag>
            
            <el-input v-if="row.inputVisble"  class="input-new-tag" ref="saveTagInput" v-model="inputValue"  size="small"
              @keyup.enter.native="handleInputConfirm(row)"
              @blur="handleInputConfirm(row)"
            >
            </el-input>
            <el-button v-else class="button-new-tag" size="small" @click="showInput(row)">+ New Tag</el-button>
                        
            </template>
          </el-table-column>
            <!-- 操作 -->
            <el-table-column label="操作">
              <template slot-scope="{row,$index}"> 
              <Lzbutton title="删除" type="danger" icon="el-icon-delete" size="small" @click="defaultAttri.splice($index,1)"></Lzbutton>
           </template>
            </el-table-column>
        </el-table>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="save">保存</el-button>
        <!-- <el-button @click="$emit('updata:controlShow',false)">取消</el-button> -->
        <el-button @click="pageCancel">取消</el-button>
      </el-form-item>
    </el-form>
    
  </div>
</template>

<script>
import _ from 'lodash'
import { spu } from '@/api';
export default {
  
  name: "addSpu",
  data() {
    return {
      // 修改后的属性值列表
      defaultAttri:[],
      // 临时参数
      temp: "",
      spuFrom: {
        name: "",
        
        goods_brief: "",
        brand_id:"",
        // 属性值名称列表
        attributeList: [
          ],
      },
      //   upload
      dialogImageUrl: "",
      dialogVisible: false,
      disabled: false,
      // 列表相关
      brandList: [],
      attributeList: [],
      category_id: "",
      // tag
      inputVisible: false,
      inputValue: '',
      //请求来的图片地址
      imageList:[],
      
    };
    
  },

  props: ["controlShow"],
  methods: {
    // upload
    picsUpdate(res,files,fileslist){
      let ChangeImg = {
        url:files.response.data,
        name:files.name,
        pic_list:files.response.data.replace('/dev-api','/api')
      }
      this.imageList.push(ChangeImg)
      
    },


    handleRemove(res,files,fileslist) {
      this.imageList = files
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },



    // 创建商品请求
    async AddHandle(category_id) {
      this.category_id = category_id;
      this.spuFrom = {
        name: "",
        brand_id: "",
        goods_brief: "",
        // 属性值名称列表
        attributeList: [
          ]}

          
      if (this.category_id != "") {
        try {
          let { data } = await this.$api.sku.reqBrand();
          this.brandList = data;
          let result = await this.$api.sku.reqSpuNopagination(category_id);
          this.attributeList = result.data;
        } catch {
          this.$message.error("请求数据出错!");
        }
      } else {
        this.$message.warning("请选择分类");
      }
    },
    // 修改商品
    async editSpu(row){
      this.category_id = row.category_id
      let temp = _.cloneDeep(row)
      this.spuFrom = {...temp}
        try {
         let result = await this.$api.sku.reqSpuNopagination(row.category_id);
          this.attributeList = result.data;
         let sale =await this.$api.sku.reqSpuSale(row.id)
          // this.spuFrom.attributeList = sale.data
          this.defaultAttri = sale.data
         let { data } = await this.$api.sku.reqBrand();
          this.brandList = data; 
          let pics  =await this.$api.sku.reqGoodsPics(row.id)    
          this.imageList = pics.data
        } catch {
          this.$message.error("请求数据出错!");
        }
    },
    // tag相关
    // 删除属性值列表

      showInput(row,$index) {
        this.$set(row,'inputVisble',true)
        this.$nextTick(_ => {
          this.$refs.saveTagInput.focus();
          
        });        

      },
      // 添加属性值,失焦时
      handleInputConfirm(row) {
       
        if(this.inputValue.trim() == ''){
          this.$set(row,'inputVisble',false)
         return this.inputValue =''
        }else if(row.attri.some(item => item.value == this.inputValue)){
          this.$message.warning('不能输入相同值')
          this.inputValue = ''
          
          return 
        }
        else{
           let inputValue = {
          category_id:this.category_id,
          goods_id:this.spuFrom.id,
          sale_attribute: row.sale_attribute,
          value:this.inputValue
        };

          row.attri.push(inputValue);
          this.$set(row,'inputVisble',false)
          return this.inputValue = '';
        }
      },


        /*
        {__ob__: Observer}
        attri: Array(1)
        0:
        category_id: 1008002
        goods_id: 1135054
        id: 1
        sale_attribute: 5
        value: "GB18401-2010 B类"

        0:
        category_id: 1008002
        goods_id: 1135054
        id: 1
        sale_attribute: 5
        value: "GB18401-2010 B类"
        */

      // 添加销售属性
      addSaleAttribute(){
        let obj ={
            attri:[],
            name:this.temp.split(':')[0],
            sale_attribute:+this.temp.split(':')[1],
          }
        this.defaultAttri.push(obj)

        // let target = this.attributeList
        // let attriList = this.spuFrom.attributeList
        // let result = target.filter(item => attriList.every(citem => citem.sale_attribute !=item.id))
        // this.attributeList = result
        this.temp = ''
      },
      // 保存数据
     async save(){
        // 收集整理数据
        // defaultAttri.forEach((item,index )=>{
        //   if(item.attri.length ==0){
        //     defaultAttri.splice(index,1)
        //   }
        // })
        let {category_id,defaultAttri,spuFrom,imageList} = this
        spuFrom.category_id = category_id
        spuFrom.imageList = imageList
        spuFrom.attributeList = defaultAttri

        //  发送数据
       
        try{
          let data = await this.$api.sku.reqSaveSpu(spuFrom)
          if(data.status != 200){
            this.$message.error('修改失败')
            }
          // 同步父级控制显示窗口
            this.$message.success('修改成功')
            this.setDefault()
            // 通知父组件重新获取数据
            this.$emit('judgeSuccess')
            this.$emit('update:controlShow',false)         
        }catch{
          this.$message.error('修改失败')
        }
          
        },
        // 还原默认数据
        setDefault(){
        // 修改后的属性值列表
          this.defaultAttri=[],
          // 临时参数
          this.temp = "",
          this.spuFrom = {
            name: "",
            brand_id: "",
            goods_brief: "",
            // 属性值名称列表
            attributeList:[]
          },
          //   upload
          this.dialogImageUrl = "",
          this.dialogVisible = false,
          this.disabled = false,
          // 列表相关
          this.brandList= [],
          this.attributeList = [],
          this.category_id = "",
          // tag
          this.inputVisible = false,
          this.inputValue = '',
          //请求来的图片地址
          this.imageList = []
        },
        // 点击取消还原数据
        pageCancel(){
          this.setDefault()
          this.isCreate = false
          this.$emit('update:controlShow', false)
        }
       
   },
  computed:{
    unUseAttri(){
     return this.attributeList.filter(item => this.defaultAttri.every(citem => citem.sale_attribute !=item.id))
    }

  }

}
</script>

<style>
 .el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
</style>